jQuery(function(){

    // This demo depends on the canvas element
    if(!('getContext' in document.createElement('canvas'))){
        alert('Sorry, it looks like your browser does not support canvas!');
        return false;
    }

    var doc = jQuery(document),
        win = jQuery(window),
        canvas = jQuery('#paper'),
        ctx = canvas[0].getContext('2d'),
        instructions = jQuery('#instructions');

    // Generate an unique ID
    var id = Math.round(jQuery.now()*Math.random());

    // A flag for drawing activity
    var drawing = false;

    var clients = {};
    var cursors = {};
	
	var topic = "DrawingDemo";
	
	PSB.register({topic: topic});

	PSB.subscribe({topic: topic,
	callback: function(msg){
        if(! (msg.id in clients)){
            // a new user has come online. create a cursor for them
            cursors[msg.id] = jQuery('<div class="cursor">').appendTo('#cursors');
        }

        // Move the mouse pointer
        cursors[msg.id].css({
            'left' : msg.x,
            'top' : msg.y
        });

        // Is the user drawing?
        if(msg.drawing && clients[msg.id]){

            // Draw a line on the canvas. clients[data.id] holds
            // the previous position of this user's mouse pointer

            drawLine(clients[msg.id].x, clients[msg.id].y, msg.x, msg.y);
        }

        // Saving the current client state
        clients[msg.id] = msg;
        clients[msg.id].updated = jQuery.now();
    }});

    var prev = {};

    canvas.on('mousedown',function(e){
        e.preventDefault();
        drawing = true;
        prev.x = e.pageX;
        prev.y = e.pageY;

        // Hide the instructions
        instructions.fadeOut();
    });

    doc.bind('mouseup mouseleave',function(){
        drawing = false;
    });

    var lastEmit = jQuery.now();

    doc.on('mousemove',function(e){
        if(jQuery.now() - lastEmit > 30){
            PSB.publish({topic: topic, message: {
                'x': e.pageX,
                'y': e.pageY,
                'drawing': drawing,
                'id': id
            }});
            lastEmit = jQuery.now();
        }

        // Draw a line for the current user's movement, as it is
        // not received in the socket.on('moving') event above

        if(drawing){

            drawLine(prev.x, prev.y, e.pageX, e.pageY);

            prev.x = e.pageX;
            prev.y = e.pageY;
        }
    });

    // Remove inactive clients after 10 seconds of inactivity
    setInterval(function(){

        for(ident in clients){
            if(jQuery.now() - clients[ident].updated > 10000){

                // Last update was more than 10 seconds ago.
                // This user has probably closed the page

                cursors[ident].remove();
                delete clients[ident];
                delete cursors[ident];
            }
        }

    },10000);

    function drawLine(fromx, fromy, tox, toy){
        ctx.moveTo(fromx, fromy);
        ctx.lineTo(tox, toy);
        ctx.stroke();
    }

});